package com.csit.service.impl;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.csit.bean.Pager;
import com.csit.dao.BuyDetailDao;
import com.csit.entity.Buy;
import com.csit.entity.BuyDetail;
import com.csit.entity.Product;
import com.csit.service.BuyDetailService;
import com.csit.util.ListAndJsonUtil;
import com.csit.util.StringUtil;

@Service
public class BuyDetailServiceImpl extends BaseServiceImpl<BuyDetail, Integer> implements BuyDetailService {

	@Resource
	private BuyDetailDao buyDetailDao;
	
	@Resource
	public void setBaseDao(BuyDetailDao buyDetailDao) {
		super.setBaseDao(buyDetailDao);
	}

	public String queryBuyDetail(Integer pageNumber, Integer pageSize,Buy buy,Date beginDate,Date endDate) {
		Pager pager = new Pager(pageNumber, pageSize);
		pager = buyDetailDao.queryBuyDetail(pager, buy, beginDate, endDate);
		String[] propertiesName = {"buy.buyID","buy.buyCode","buy.supplierName","buy.buyer","buy.buyDate","buy.storeHouseName",
						           "quantity","price","amount","product.productName","product.productSize","product.unitName"};
		String jsonArray = ListAndJsonUtil.getJSONString(pager.getList(), propertiesName, pager.getTotalCount());
		return jsonArray;
	}

	public String queryBuyDetail(Integer pageNumber, Integer pageSize, Buy buy,String productids, Date beginDate, Date endDate) {
		Pager pager = new Pager(pageNumber, pageSize);
		BuyDetail buyDetail = new BuyDetail();
		if(StringUtil.isNotNull(productids)){
			Product product = new Product();
			product.setProductID(Integer.parseInt(productids));
			buyDetail.setProduct(product);
		}
		pager = buyDetailDao.queryBuyDetail(pager, buy,buyDetail,beginDate, endDate);
		String[] propertiesName = {"buy.buyID","buy.buyCode","buy.supplierName","buy.buyer","buy.buyDate","buy.storeHouseName",
						           "quantity","price","amount","product.productName","product.productSize","product.unitName"};
		
		Map<String, Double> map = buyDetailDao.queryTotal(buy, buyDetail, beginDate, endDate);
		Double totalQty = map.get("totalQty");
		Double totalAmount = map.get("totalAmount");
		
		String jsonArray = ListAndJsonUtil.getJSONString(pager.getList(), propertiesName, pager.getTotalCount());
		
		StringBuilder json = new StringBuilder(jsonArray.substring(0, jsonArray.length()-1));
		json.append(",\"footer\":[{\"unitName\":\"统计\",\"quantity\":").append(totalQty).append(",\"amount\":").append(totalAmount).append("}]}");
		return json.toString();
	}

	public Map<String, Double> countBuyDetail(Buy buy, Date beginDate,Date endDate) {
		BuyDetail buyDetail = new BuyDetail();
		return buyDetailDao.queryTotal(buy, buyDetail, beginDate, endDate);
	}
}
